package cn.lyq.card.manager

import android.widget.TextView
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import cn.lyq.card.R
import cn.lyq.card.data.model.ResponseInfo
import cn.lyq.card.data.repository.Repository
import com.blankj.utilcode.util.ToastUtils
import kotlinx.coroutines.*


object PhoneCodeManager {

    /** 验证码倒计时*/
    var countDown = MutableLiveData(0)

    fun sendMsgCode(type: Int) {
        send {
            Repository.userService.sendCode(type.toString())
        }
    }

    fun getMsgCode(phone: String, type: Int) {
        send {
            Repository.userService.getCode(phone, type.toString())
        }
    }

    private fun send(block: suspend () -> ResponseInfo<Nothing>) {
        if (countDown.value != 0) {
            return
        }
        GlobalScope.launch(Dispatchers.Main) {
            try {
                val data = block()
                if (data.isOk()) {
                    countDown.value = 60
                    ToastUtils.showShort(data.msg)
                    startCountDown()
                } else {
                    countDown.value = 0
                    ToastUtils.showShort("获取验证码失败:${data.msg}")
                }
            } catch (e: Exception) {
                countDown.value = 0
                ToastUtils.showShort("获取验证码失败")
            }
        }
    }

    private suspend fun startCountDown() {
        while (countDown.value != 0) {
            withContext(Dispatchers.IO) {
                delay(1000)
            }
            val i = countDown.value?.minus(1) ?: 0
            if (i < 0){
                countDown.value = 0
            }else{
                countDown.value = i
            }
        }
    }

    fun observer(tvGetCode: TextView): Observer<Int> {
        return Observer {
            if (it == null) {
                tvGetCode.isEnabled = true
                tvGetCode.setText(R.string.str_get_code)
            } else {
                if (it == 0) {
                    tvGetCode.isEnabled = true
                    tvGetCode.setText(R.string.str_get_code)
                } else {
                    tvGetCode.isEnabled = false
                    tvGetCode.text = "重新获取($it)"
                }
            }
        }
    }

    fun reset() {
        countDown.postValue(0)
    }
}